//
//  UserOauthModel.swift
//  WeiBoOfSwift
//
//  Created by aven wu on 23/04/2018.
//  Copyright © 2018 GML. All rights reserved.
//

import UIKit

struct UserOauthModel: Codable {
    // 用户授权的唯一票据，用于调用微博的开放接口，
    var access_token:String?
    // access_token的生命周期，单位是秒数。
    var expires_in:Int?
    // 授权用户的UID，
    var uid:String?
    var remind_in:String?
    var isRealName:String?
    
    static let filePath = "account.db".cacheDir()
    static var account:UserOauthModel?
    /********微博返回数据*****/
    var screen_name:String?
    var description:String?
    var avatar_large:String?
    
    /*
     判断用户是否登录
     */
    static func userLogin() -> Bool {
        return UserOauthModel.readAccount() != nil
    }
    
    func saveAccount(jsonData:Data) -> Void {
        NSKeyedArchiver.archiveRootObject(jsonData, toFile: UserOauthModel.filePath)

    }
     static func readAccount() -> UserOauthModel? {
        if account != nil {
            return account
        }
        if let auccountData = NSKeyedUnarchiver.unarchiveObject(withFile: UserOauthModel.filePath) as? Data {
            account = try? JSONDecoder().decode(self, from: auccountData)
            return account
        }
        return nil
        
    }
    
    func requestUserInfo(params:[String:Any],finished: @escaping (_ accountModel:UserOauthModel?,_ error:Error?) -> ()) -> Void {
        
        let path = "/2/users/show.json"
//        let params = ["access_token":access_token,"uid":uid]
        NetWorkTools.shareNetWorkTools().get(path, parameters: params, progress:nil, success: { (_, json) in
           var dic = json as! [String:Any]
            for (key,value) in params {
                dic[key] = value
            }
            let jsonData = try? JSONSerialization.data(withJSONObject: dic, options: JSONSerialization.WritingOptions.prettyPrinted)
            let userModel = try? JSONDecoder().decode(UserOauthModel.self, from: jsonData!)
            // 保存模型
            userModel?.saveAccount(jsonData:jsonData!)
            finished(userModel, nil)
        }) { (_, error) in
            finished(nil,error)
        }
        
    }
    
//    func encode(to encoder:Encoder) throws {
//        var container = encoder.container(keyedBy:  Key.self)
//        try container.encode(access_token, forKey: .access_token)
//        try container.encode(expires_in, forKey: .expires_in)
//        try container.encode(uid, forKey: .uid)
//        try container.encode(remind_in, forKey: .remind_in)
//
//    }
//
//    init(from decoder: Decoder) throws {
//        let container = try decoder.container(keyedBy: CodingKeys.self)
//        access_token = try container.decode(String.self, forKey: .access_token)
//        uid = try container.decode(String.self, forKey: .uid)
//        expires_in = try container.decode(String.self, forKey: .expires_in)
//        // remind_in
//        remind_in = try container.decode(String.self, forKey: .remind_in)
//    }
    
    
    
    
}

